package com.yao.club.service.impl;

import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.GoodsFootPrintRecord;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.GoodsFootPrintRecordRepository;
import com.yao.club.service.GoodsFootPrintService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.Date;
import java.util.List;

@Service
public class GoodsFootPrintServiceImpl implements GoodsFootPrintService {

    @Autowired
    private GoodsFootPrintRecordRepository footPrintRepository;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public ResponseEntity<Boolean> addFootPrint(Long goodsId, String username) {
        try {
            // 获取用户信息
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            // 查找是否存在今天的浏览记录
            GoodsFootPrintRecord existingRecord = footPrintRepository
                .findByGoodsIdAndUserIdAndDate(goodsId, user.getMember_id());

            if (existingRecord != null) {
                // 如果今天已经有浏览记录，更新浏览时间
                existingRecord.setCreatedAt(Instant.now());
                existingRecord.setViewCount(existingRecord.getViewCount() + 1);
                footPrintRepository.save(existingRecord);
            } else {
                // 创建新的浏览记录
                GoodsFootPrintRecord newRecord = new GoodsFootPrintRecord();
                newRecord.setGoodsId(goodsId);
                newRecord.setUserId(user.getMember_id());
                newRecord.setCreatedAt(Instant.now());
                newRecord.setViewCount(1);
                footPrintRepository.save(newRecord);
            }

            return ResponseUtils.success(true);
        } catch (Exception e) {
            return ResponseUtils.failed("添加浏览记录失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<ResultEntity<GoodsFootPrintRecord>> getFootPrints(String username) {
        try {
            // 获取用户信息
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            List<GoodsFootPrintRecord> footPrints = footPrintRepository.findByUserId(user.getMember_id());
            ResultEntity<GoodsFootPrintRecord> result = new ResultEntity<>();
            result.setRecords(footPrints);
            result.setTotal(footPrints.size());
            return ResponseUtils.success(result);
        } catch (Exception e) {
            return ResponseUtils.failed("获取足迹失败：" + e.getMessage());
        }
    }
} 